package com.uuj.dome.Entity;


import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * ClassName:UserEntitiy
 * PACKAGE_NAME:com.uuj.dome.Entity
 */
@Entity
@Table(name = "users")
public class UserEntitiy implements Serializable, UserDetails {

    @Id
    @Column(name = "u_id")
    private Integer id;
    @Column(name = "u_name")
    private String username;
    @Column(name = "u_password")
    private String password;
    @ManyToMany
    @JoinTable(name = "user_roles",
            joinColumns = {@JoinColumn(name = "ur_user_id")},
    inverseJoinColumns = {@JoinColumn(name = "ur_roles_id")})
    private List<RoleEntity> roles;



    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        List<RoleEntity> roles = getRoles();
        roles.forEach(roleEntity -> {
            list.add(new SimpleGrantedAuthority(roleEntity.getFlag()));});

        return list;
    }

    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<RoleEntity> getRoles() {
        return roles;
    }

    public void setRoles(List<RoleEntity> roles) {
        this.roles = roles;
    }
}
